package com.example.demo.service;

import com.example.demo.model.Student;

import com.example.demo.repository.StudentRepository;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.domain.Example;

import org.springframework.stereotype.Service;

import java.util.List;

@Service

public class StudentService {

    @Autowired

    private StudentRepository studentRepository;

    public List<Student> list() {

        return studentRepository.findAll();

    }

    public void delete(Integer id) {

        studentRepository.deleteById(id);

    }

    public void save(Student s) throws Exception {

        if (studentRepository.findByTel(s.getTel()).size() > 0) {

            throw new Exception("Tel already exists");

        }

        studentRepository.save(s);

    }

    public Student get(Integer id) {

        return studentRepository.getReferenceById(id);

    }

    public void update(Student s) throws Exception {

        List<Student> students = studentRepository.findByTel(s.getTel());

        if (students.size() > 1) {

            throw new Exception("Tel already exists");

        } else if (students.size() == 1) {

            if (!students.get(0).getId().equals(s.getId())) {

                throw new Exception("Tel already exists");

            }

        }

        studentRepository.save(s);

    }

    public List<Student> search(Student s) {

        return studentRepository.findAll(Example.of(s));

    }

}